// var playOb = document.createElement("audio");
playOb = document.getElementById('audio');
xhr = new XMLHttpRequest();
if (playOb == null) {
    console.log("创建audio对象");
    playOb = new Audio();
}

playOb.autoplay = true;
playOb.controls = true;
playOb.loop = true;
console.log(playOb);
var canvas = document.createElement("canvas");
canvas.onMouseMove = MouseMoveCheck;
console.log(canvas);
var ctx = canvas.getContext("2d");
// ctx.fillStyle = "rgb(200,0,0)";
//绘制矩形
// ctx.fillRect (10, 10, 55, 50);

// ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
// ctx.fillRect (30, 30, 55, 50);
// ctx.strokeRect(10, 70, 100, 50);
// chrome.storage.sync.get('playMusic', (res) => {console.log(res);})

const playbaseTable = {
    baseName: 'localMusic', // 数据库名称
    sheetName: 'playInventory', // 数据表名称
    keyName: 'songName', // 主键
    indexArr: [
        {name: 'songIndex', unique: true},
        {name: 'songName', unique: false},
        {name: 'songPath', unique: false},
        {name: 'songStatus', unique: false}
    ] // 索引
}


const songbaseTable = {
    baseName: 'localMusic', // 数据库名称
    sheetName: 'songs', // 数据表名称
    keyName: '', // 主键
    indexArr: [
        {name: 'songIndex', unique: true},
        {name: 'songName', unique: false},
        {name: 'songPath', unique: false},
        {name: 'songDesc', unique: false}
    ] // 索引
}
var playNewtab = new IndexedMyDB(playbaseTable);
var songNewTable = new IndexedMyDB(songbaseTable);
const port = chrome.runtime.connect();
console.log(port);
port.name = "content" 
port.postMessage({ content: "content" })

chrome.runtime.onConnect.addListener(function(port) {
    console.assert(port.name == "yisheng");
    port.onMessage.addListener(function(msg) {
        if (msg.joke == "Knock knock")
            port.postMessage({question: "Who's there?"});
        else if (msg.answer == "Madame")
            port.postMessage({question: "Madame who?"});
        else if (msg.answer == "Madame... Bovary")
            port.postMessage({question: "I don't get it."});
    });
});


function MouseMoveCheck(event){
    console.log(event);
}

function DBAction(){
    let db;

    //先删除
    window.indexedDB.deleteDatabase('localMusic')

    const req = window.indexedDB.open('localMusic');

    req.onerror = function (event) {
        console.log('打开数据库失败');
    };

    req.onsuccess = function (event) {
        console.log('打开数据库成功');
        db = event.target.result;
        db.transaction( ['city'] );

    };

    req.onupgradeneeded = function (event) {
        console.log('升级成功');
        db = event.target.result;
        db.createObjectStore('songs',{keyPath:'song_id'});
    }
}


var theSongIndex = 0
var song_list = new Array();
function injectedFunction(color) {
    document.body.style.backgroundColor = color;
}



chrome.storage.onChanged.addListener(function(changes, namespace) {
    for (var key in changes) {
        var storageChange = changes[key];
        console.log('Storage key "%s" in namespace "%s" changed. ' +'Old value was "%s", new value is "%s".',
        key,
        namespace,
        storageChange.oldValue,
        storageChange.newValue);
    }
});

chrome.runtime.onMessage.addListener(function (request,sender,callback) {
    let playInfo = {}
    
    var playIndex = 0;
    var playName = null;
    var playPath = null;
    var playStatus = null;
    var actionInfo = "";

    console.log("request",request);
    console.log("sender",sender);
    if (request.eventType == "MenuClick"){
        actionInfo = request.greeting.menuItemId
    }else if (request.eventType == "command"){
        actionInfo = request.greeting
    }
    // AddPlayStatus("content "+actionInfo);
    chrome.storage.sync.get('playMusic', (res) => {
        console.log(res);
        

    })

    if (song_list.length == 0){
        const s = GetMusicList();
        console.log(s);
    }
    
    
    

    if (playOb.readyState == 0) {
        console.log("当前未播放，清除缓存");
        chrome.storage.sync.clear();
    }

    chrome.storage.sync.get('playMusic', (res) => {
        console.log(res);
    })

        
    if (actionInfo == "playSong" ){
        console.log(xhr.readyState, xhr.status);
        chrome.storage.sync.get('playMusic', (res) => {
            console.log(res);
            if  (res.playMusic == "pause"){
                console.log("继续播放");
                Play();
                AddPlayStatus("play");
                playIndex = theSongIndex;
                playPath = song_list[theSongIndex].path;
                playName = song_list[playIndex].name;
                playStatus = "play";
            } else if(res.playMusic == "play"){
                console.log("正在播放中。。。。");
            } else if ((res.playMusic == undefined || res.playMusic == "pause")  && song_list.length > 0){
                playOb.src = "http://localhost:1987/music"+song_list[theSongIndex].path;
                console.log("开始播放"+song_list[0].name);
                sendmessage("开始播放"+song_list[0].name);
                playPath = song_list[theSongIndex].path;
                playName = song_list[0].name;
                playStatus = "play";
                Play();
                AddPlayStatus("play");
            } else {
                console.log("未获取到歌曲");
            }
        });

    }else if (actionInfo == "nextSong" && theSongIndex < song_list.length){
        theSongIndex +=1
        song = song_list[theSongIndex]
        playOb.src = "http://localhost:1987/music"+song.path;
        console.log("播放下一曲",song);
        Play();
        playIndex = theSongIndex;
        playPath = song_list[theSongIndex].path;
        playName = song_list[theSongIndex].name;
        playStatus = "play";
        
    }else if (actionInfo == "prevSong" && theSongIndex > 1){
        theSongIndex -=1
        playOb.src = "http://localhost:1987/music"+song_list[theSongIndex ].path;
        console.log("播放上一曲");
        Play();
        playIndex = theSongIndex;
        playPath = song_list[theSongIndex].path;
        playName = song_list[playIndex].name;
        playStatus = "play";
    }else if (actionInfo == "pauseSong"){
        console.log("暂停播放");
        playOb.pause();
        AddPlayStatus("pause");
        playIndex = theSongIndex;
        playPath = song_list[theSongIndex].path;
        playName = song_list[playIndex].name;
        playStatus = "pause";

    }
    
    playNewtab.isReady().then(() => {
        return playNewtab.update(
            {
                songIndex:playIndex,
                songName:playName,
                songPath:playPath,
                songStatus:playStatus
            }
        )
    }).then(() => {
        playNewtab.destroy()
    }).catch(e=> {
        console.error(e)
    }) 
    callback({message: "i'm callback content"});
    return
});

chrome.storage.local.get("playMusic", function (result) {
    console.log(result);
    return
});

function AddPlayStatus(msg){
    chrome.storage.local.set({'playMusic' : msg,'platfrom':"centent"}, () => {
        console.log('set successed!');
    });
    chrome.storage.sync.set({'playMusic' : msg,'platfrom':"options"}, () => {
        console.log('set successed!');
    });
}

function Play(){
    playOb.addEventListener("ended", playNextSong);
    const promise = playOb.play();
    if (promise === undefined) {
        return;
    }
    promise.then(() => {}).catch(error => {
        if (error.name === 'NotAllowedError') {}
    });
}

function playNextSong() {
    theSongIndex +=1
    song = song_list[theSongIndex]
    playOb.src = "http://localhost:1987/music"+song.path;
    console.log("播放下一曲",song);
    playIndex = theSongIndex;
    playPath = song_list[theSongIndex].path;
    playName = song_list[theSongIndex].name;
    playStatus = "play";



    const promise =playOb.play();
    if (promise === undefined) {
        return;
    }
    promise.then(() => {}).catch(error => {
        if (error.name === 'NotAllowedError') {}
    });

    playNewtab.isReady().then(() => {
        return playNewtab.update(
            {
                songIndex:playIndex,
                songName:playName,
                songPath:playPath,
                songStatus:playStatus
            }
        )
    }).then(() => {
        playNewtab.destroy()
    }).catch(e=> {
        console.error(e)
    }) 
}




function sendmessage(msg){
    var msg = {content:msg,from:"content",audio:playOb};
    var my_options = null;
    chrome.runtime.sendMessage(null,msg,my_options,function(response) {
        console.log('content get response:',response);
    });
}


function GetMusicList(){
    window.indexedDB.deleteDatabase('localMusic')
    console.log("获取音乐列表");
    
    // if  (song_list.ength != 0){
    //     console.log("歌曲已获取过");
    //     return 
    // }

    
    xhr.timeout = 3000;
    xhr.open('GET', 'http://localhost:1987/getMyMusic', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const responseData = JSON.parse(xhr.responseText); 
            var newList = document.createElement("select");
            newList.setAttribute('id', 'selectId');
            
            newList.size = "20";
            let {code,msg,songs} = responseData;
            // console.log(code,msg,songs);
            

            for(let i = 0;i< songs.length;i++){
                let song = songs[i];
                song_list.push(song);
                // newList.appendChild(new Option(song.name,song.path));
                var opt = new Option(song.name, song.path)
                newList.options.add(opt);
                // console.log(song);
                songNewTable.isReady().then(() => {
                    songNewTable.update({
                        songIndex:i,
                        songName: song.name,
                        songPath: song.path
                    })
                }).then(() => {
                    songNewTable.destroy()
                }).catch(e=> {
                    console.error(e)
                })
            }

            newList.onchange = function (item) {
                // showDiv('other');
                var selectId = document.getElementById("selectId");
                var index = selectId.selectedIndex
                playOb.src = "http://localhost:1987/music"+songs[index].path;
            }
            newList.onselect = function(item) {
                // showDiv('other');
                console.log("onselect"+item);
            }
            newList.onclick = function(item) {
                // showDiv('other');
                console.log(item);
            }
            chrome.storage.sync.get('playMusic', (res) => {
                console.log(res);
                if ((res.playMusic == undefined || res.playMusic == "pause")  && song_list.length > 0){
                    playOb.src = "http://localhost:1987/music"+song_list[theSongIndex].path;
                    console.log("开始播放"+song_list[0].name);
                    sendmessage("开始播放"+song_list[0].name);
                    playPath = song_list[theSongIndex].path;
                    playName = song_list[0].name;
                    playStatus = "play";
                    Play();
                    AddPlayStatus("play");
                }
            })
        }else{
            console.log("出现异常",xhr.readyState,xhr.status)
            return 3
        }
    };
    xhr.ontimeout = function(event){
        alert('请求超时！');
        return 2
    }
    xhr.send();
    return 1
}
function RandomNumber() {
    return Math.floor(Math.random() * 100000000.0)
}